Ext.onReady(function(){
    Ext.QuickTips.init();
    Ext.BLANK_IMAGE_URL = 'ext3.2/resources/images/default/s.gif';
    var gridTitle = '企业产品管理';
    var findall = "corpProducts_all.do";
    var getNewIdUrl = "corpProducts_newId.do";
    var addMsg = 'corpProducts_add.do';
    var deleteMsg = 'corpProducts_delete.do';
    var modifyMsg = 'corpProducts_modify.do';
    
    var renderTo = 'corpproducts_grid';
    var seqValue = "corp_products_seq"; // 序列号名称
    var identityName = "id"; // 主键名称
    var pageSize = 18;
    var gridHeight = 500;
    var sm = new Ext.grid.CheckboxSelectionModel();
    var cm = new Ext.grid.ColumnModel([sm, {
        header: "编号",
        width: 100,
        dataIndex: 'id'
    }, {
        header: "产品名称",
        width: 100,
        sortable: true,
        dataIndex: 'productName'
    }, {
        header: "产品描述",
        width: 100,
        dataIndex: 'content'
    }, {
        header: "点击率",
        width: 100,
        dataIndex: 'clickNum'
    }, {
        header: "排序",
        width: 100,
        dataIndex: 'sequence'
    }, {
        header: "是否推荐",
        width: 100,
        dataIndex: 'isCommFlag'
    }, {
        header: "是否新产品",
        width: 100,
        dataIndex: 'isNewFlag'
    }, {
        header: "添加时间",
        width: 100,
        dataIndex: 'addTime'
    }, {
        header: "修改时间",
        width: 100,
        dataIndex: 'updateTime'
    }, {
        header: "产品编号",
        width: 100,
        dataIndex: 'productNo'
    }, {
        header: "产品型号",
        width: 100,
        dataIndex: 'productModel'
    }, {
        header: "产品价络",
        width: 100,
        dataIndex: 'nPrice'
    }, {
        header: "代理价络",
        width: 100,
        dataIndex: 'pPrice'
    }, {
        header: "存货",
        width: 100,
        dataIndex: 'stock'
    }, {
        header: "单位名称",
        width: 100,
        dataIndex: 'unitName'
    }, {
        header: "产品小图",
        width: 100,
        dataIndex: 'smallPic'
    }, {
        header: "产品大图",
        width: 100,
        dataIndex: 'bigPic'
    }, {
        header: "产品市场",
        width: 100,
        dataIndex: 'marker'
    }, {
        header: "产品关键字",
        width: 100,
        dataIndex: 'keyword'
    }, {
        header: "产品类型",
        width: 100,
        dataIndex: 'productType'
    }, {
        header: "审核",
        width: 100,
        dataIndex: 'isAuditing'
    }]);
    
    var Struct = Ext.data.Record.create([{
        name: 'id',
        type: 'int'
    }, {
        name: 'productName',
        type: 'string'
    }, {
        name: 'content',
        type: 'string'
    }, {
        name: 'clickNum',
        type: 'int'
    }, {
        name: 'sequence',
        type: 'int'
    }, {
        name: 'isCommFlag',
        type: 'int'
    }, {
        name: 'isNewFlag',
        type: 'int'
    }, {
        name: 'addTime',
        type: 'date'
    }, {
        name: 'updateTime',
        type: 'date'
    }, {
        name: 'corpId',
        type: 'string'
    }, {
        name: 'sortId',
        type: 'string'
    }, {
        name: 'productNo',
        type: 'string'
    }, {
        name: 'productModel',
        type: 'string'
    }, {
        name: 'nPrice',
        type: 'int'
    }, {
        name: 'pPrice',
        type: 'int'
    }, {
        name: 'stock',
        type: 'int'
    }, {
        name: 'unitName',
        type: 'string'
    }, {
        name: 'smallPic',
        type: 'string'
    }, {
        name: 'bigPic',
        type: 'string'
    }, {
        name: 'marker',
        type: 'string'
    }, {
        name: 'keyword',
        type: 'string'
    }, {
        name: 'productType',
        type: 'string'
    }]);
    
    var reader = new Ext.data.JsonReader({
        root: 'rows', // rows : 为服务器端传送过来的记录数值对象
        totalProperty: 'total' // results 为服务器端json传送过来的记录的行数, count(*)运算
    }, ['id', 'productName', 'content', 'clickNum', 'sequence', 'isCommFlag', 'isNewFlag', 'addTime', 'updateTime', 'corpId', 'sortId', 'productNo', 'productModel', 'nPrice', 'pPrice', 'stock', 'unitName', 'smallPic', 'bigPic', 'marker', 'keyword', 'productType','isAuditing']);
    
    
    
    //分类 信息
    var dictIdNamesReader = new Ext.data.JsonReader({
        root: 'ids'
    }, ['id', 'name']);
    
    var dictIdNamesStore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            method: 'GET',
            url: '../../system/appDict_ids.do?distcode=1004'
        
        }),
        reader: dictIdNamesReader
    
    });
    
    
    function addHandler(){
        var newId;
        var conn = new Ext.data.Connection();
        conn.request({
            url: getNewIdUrl,
            params: {
                seqName: seqValue
            },
            success: function(resp, opt){
                newId = Ext.util.JSON.decode(resp.responseText).newId;
                openCreateWin(newId);
            },
            failure: function(resp, opt){
                Ext.Msg.alert('Error', '获取新id失败');
            }
        })
    }
    
    // add handle to deal with add action
    var openCreateWin = function(newId){
        var win;
        var f = new Ext.form.FormPanel({
            title: "添加信息",
            height: 420,
            autoWidth: true,
            labelWidth: 75,
            labelAlign: "center",
            frame: true,
            defaultType: 'textfield',
            fileUpload: true,
            enctype: 'multipart/form-data',
            defaults: {
                width: 350
            },
            buttonAlign: 'center',
            items: [{
                xtype: 'tabpanel',
                plain: true,
                activeTab: 0,
                height: 380,
                autoWidth: true,
                deferredRender: false,
                defaults: {
                    bodyStyle: 'padding:10px'
                },
                items: [{
                    title: '基本信息',
                    layout: 'form',
                    defaults: {
                        width: 300
                    },
                    defaultType: 'textfield',
                    items: [{
                        fieldLabel: '编号',
                        name: 'corpProducts.id',
                        readOnly: true,
                        value: newId
                    }, {
                        fieldLabel: '产品名称',
                        name: 'corpProducts.productName',
                        allowBlank: false
                    }, new Ext.form.TextArea({
                        fieldLabel: '产品介绍',
                        name: 'corpProducts.content',
                        width: 300,
                        height: 60
                    }), new Ext.form.NumberField({
                        fieldLabel: '产品编号',
                        name: 'corpProducts.productNo'
                    }), new Ext.form.TextArea({
                        fieldLabel: '产品型号',
                        name: 'corpProducts.productModel',
                        width: 300,
                        height: 50
                    }), new Ext.form.NumberField({
                        fieldLabel: '排序',
                        name: 'corpProducts.sequence'
                    }), {
                        xtype: 'combo',
                        fieldLabel: '分类',
                        hiddenName: "corpProducts.sortId",
                        name: 'corpProducts.sortId',
                        store: dictIdNamesStore,
                        emptyText: '请选择',
                        valueField: 'id',
                        displayField: 'name',
                        editable: false,
                        forceSelection: true,
                        triggerAction: 'all',
                        allowBlank: false
                    }]
                }, {
                    title: '其他信息',
                    layout: 'form',
                    defaults: {
                        width: 300
                    },
                    defaultType: 'textfield',
                    
                    items: [new Ext.form.NumberField({
                        fieldLabel: '产品价络',
                        name: 'corpProducts.nPrice'
                    }), new Ext.form.NumberField({
                        fieldLabel: '代理价络',
                        name: 'corpProducts.pPrice'
                    }), new Ext.form.NumberField({
                        fieldLabel: '存货',
                        name: 'corpProducts.stock',
                        allowBlank: false,
                        blankText: '必填字段'
                    }), {
                        fieldLabel: '单位名称',
                        name: 'corpProducts.unitName'
                    }, {
                        fieldLabel: '产品小图',
                        name: 'smallPic',
                        inputType: 'file'
                    }, {
                        fieldLabel: '产品大图',
                        name: 'bigPic',
                        inputType: 'file'
                    }, {
                        fieldLabel: '产品市场',
                        name: 'corpProducts.marker'
                    }, {
                        fieldLabel: '产品关键字',
                        name: 'corpProducts.keyword'
                    }, {
                        fieldLabel: '产品类型',
                        name: 'corpProducts.productType'
                    }, {
                        xtype: 'radiogroup',
                        fieldLabel: '是否推荐',
                        items: [{
                            boxLabel: '是',
                            name: 'corpProducts.isCommFlag',
                            checked: true,
                            inputValue: 1
                        }, {
                            boxLabel: '否',
                            name: 'corpProducts.isCommFlag',
                            inputValue: 0
                        }]
                    }, {
                        xtype: 'radiogroup',
                        fieldLabel: '是否新品',
                        items: [{
                            boxLabel: '是',
                            name: 'corpProducts.isNewFlag',
                            checked: true,
                            inputValue: 1
                        }, {
                            boxLabel: '否',
                            name: 'corpProducts.isNewFlag',
                            inputValue: 0
                        }]
                    }]
                }],
                buttons: [{
                    text: "提交",
                    handler: s
                }, {
                    text: "重置",
                    handler: function(){
                        f.form.reset();
                    }
                }]
            
            }]
        });
        
        function s(){
            f.form.submit({
                waitTitle: "请稍候",
                waitMsg: "正在提交表单数据，请稍候.......",
                url: addMsg,
                success: function(action, form){
                    Ext.MessageBox.alert('提示信息', '数据已经成功提交！', function close(){
                        win.close();
                        location.replace(location.href);
                    });
                },
                failure: function(f, a){
                    Ext.MessageBox.alert('提示信息', "数据添加失败！");
                }
            });
            
        }
        
        if (!win) {
            win = new Ext.Window({
                title: '信息录入',
                width: 500,
                height: 480,
                x: 100,
                y: 50,
                closeAction: 'close',
                plain: true,
                modal: true,
                items: f
            });
        }
        win.show();
        
    };
    
    // 更新表单
    var updateFormHandler = function(){
        editor.stopEditing();
        var s = grid.getSelectionModel().getSelected();
        if (!s) 
            return false;
        var win;
        var updateForm = new Ext.form.FormPanel({
            title: "修改信息",
            height: 420,
            autoWidth: true,
            labelWidth: 75,
            labelAlign: "center",
            frame: true,
            defaultType: 'textfield',
            fileUpload: true,
            enctype: 'multipart/form-data',
            defaults: {
                width: 350
            },
            buttonAlign: 'center',
            items: [{
                xtype: 'tabpanel',
                plain: true,
                activeTab: 0,
                height: 380,
                autoWidth: true,
                deferredRender: false,
                defaults: {
                    bodyStyle: 'padding:10px'
                },
                items: [{
                    title: '基本信息',
                    layout: 'form',
                    defaults: {
                        width: 300
                    },
                    defaultType: 'textfield',
                    items: [{
                        fieldLabel: '编号',
                        name: 'corpProducts.id',
                        readOnly: true,
                        value: s.get('id')
                    }, {
                        fieldLabel: '产品名称',
                        name: 'corpProducts.productName',
                        value: s.get('productName'),
                        allowBlank: false
                    }, new Ext.form.TextArea({
                        fieldLabel: '产品介绍',
                        name: 'corpProducts.content',
                        value: s.get('content'),
                        width: 300,
                        height: 60
                    }), new Ext.form.NumberField({
                        fieldLabel: '产品编号',
                        name: 'corpProducts.productNo',
                        value: s.get('productNo')
                    }), new Ext.form.TextArea({
                        fieldLabel: '产品型号',
                        name: 'corpProducts.productModel',
                        value: s.get('productModel'),
                        width: 300,
                        height: 50
                    }), new Ext.form.NumberField({
                        fieldLabel: '排序',
                        name: 'corpProducts.sequence',
                        value: s.get('sequence')
                    }), {
                        xtype: 'combo',
                        fieldLabel: '分类',
                        hiddenName: "corpProducts.sortId",
                        name: 'corpProducts.sortId',
                        value: s.get('sortId'),
                        store: dictIdNamesStore,
                        emptyText: '请选择',
                        valueField: 'id',
                        displayField: 'name',
                        editable: false,
                        forceSelection: true,
                        triggerAction: 'all',
                        allowBlank: false
                    }]
                }, {
                    title: '其他信息',
                    layout: 'form',
                    defaults: {
                        width: 300
                    },
                    defaultType: 'textfield',
                    
                    items: [new Ext.form.NumberField({
                        fieldLabel: '产品价络',
                        name: 'corpProducts.nPrice',
                        value: s.get('nPrice')
                    }), new Ext.form.NumberField({
                        fieldLabel: '代理价络',
                        name: 'corpProducts.pPrice',
                        value: s.get('pPrice')
                    }), new Ext.form.NumberField({
                        fieldLabel: '存货',
                        name: 'corpProducts.stock',
                        value: s.get('stock'),
                        blankText: '必填字段'
                    }), {
                        fieldLabel: '单位名称',
                        name: 'corpProducts.unitName',
                        value: s.get('unitName')
                    }, {
                        fieldLabel: '产品小图',
                        name: 'smallPic',
                        value: s.get('smallPic'),
                        inputType: 'file'
                    }, {
                        fieldLabel: '产品大图',
                        value: s.get('bigPic'),
                        name: 'bigPic',
                        inputType: 'file'
                    }, {
                        fieldLabel: '产品市场',
                        name: 'corpProducts.marker',
                        value: s.get('marker')
                    }, {
                        fieldLabel: '产品关键字',
                        name: 'corpProducts.keyword',
                        value: s.get('keyword')
                    }, {
                        fieldLabel: '产品类型',
                        name: 'corpProducts.productType',
                        value: s.get('productType')
                    }, {
                        xtype: 'radiogroup',
                        fieldLabel: '是否推荐',
                        items: [{
                            boxLabel: '是',
                            name: 'corpProducts.isCommFlag',
                            checked: s.get('isCommFlag') == 1,
                            inputValue: 1
                        }, {
                            boxLabel: '否',
                            name: 'corpProducts.isCommFlag',
                            checked: s.get('isCommFlag') == 0,
                            inputValue: 0
                        }]
                    }, {
                        xtype: 'radiogroup',
                        fieldLabel: '是否新品',
                        items: [{
                            boxLabel: '是',
                            name: 'corpProducts.isNewFlag',
                            checked: s.get('isNewFlag') == 1,
                            inputValue: 1
                        }, {
                            boxLabel: '否',
                            name: 'corpProducts.isNewFlag',
                            checked: s.get('isNewFlag') == 0,
                            inputValue: 0
                        }]
                    }, {
                        name: 'corpProducts.smallPic',
                        value: s.get('smallPic'),
                        hidden: true
                    }, {
                        value: s.get('bigPic'),
                        name: 'corpProducts.bigPic',
                        hidden: true
                    }]
                }],
                buttons: [{
                    text: "提交",
                    handler: updateSubmit
                }, {
                    text: "重置",
                    handler: function(){
                        updateForm.form.reset();
                    }
                }]
            }]
        });
        
        function updateSubmit(){
            updateForm.form.submit({
                waitTitle: "请稍候",
                waitMsg: "正在提交表单数据，请稍候.......",
                url: modifyMsg,
                success: function(action, form){
                    Ext.MessageBox.alert('提示信息', '数据已经成功提交！', function close(){
                        win.close();
                        location.replace(location.href); // 重新载入数据
                    });
                },
                failure: function(f, a){
                    Ext.MessageBox.alert('提示信息', "数据添加失败！");
                }
            });
            
        }
        
        if (!win) {
            win = new Ext.Window({
                title: '信息更改',
                width: 500,
                height: 450,
                closeAction: 'close',
                plain: true,
                modal: true,
                items: updateForm
            });
        }
        win.show();
    }
    
    // -------------------------下面无需改动-----------------------------------------------------------
    
    var store = new Ext.data.Store({
        url: findall,
        reader: reader
    });
    
    var editor = new Ext.ux.grid.RowEditor({
        saveText: '保存',
        cancelText: '取消',
        listeners: {
            afteredit: function(e){
                saveHandler(e);
            }
        }
    });
    
    var grid = new Ext.grid.GridPanel({
        renderTo: renderTo,
        frame: true,
        title: gridTitle,
        autoScroll: true,
        width: "auto",
        height: gridHeight,
        store: store,
        // plugins : [ editor ],
        sm: sm,
        cm: cm,
        tbar: [{
            text: ' 增加 ',
            handler: addHandler
        }, {
            ref: '../removeBtn',
            text: ' 删除 ',
            disabled: true,
            handler: function(){
                delHandler();
            }
        }, {
            ref: '../updateBtn',
            text: ' 修改 ',
            disabled: true,
            handler: function(){
                updateFormHandler();
            }
        }],
        viewConfig: {
            columnsText: "显示/隐藏列",
            sortAscText: "正序排列",
            sortDescText: "倒序排列"
        },
        bbar: new Ext.PagingToolbar({
            pageSize: pageSize,
            store: store,
            displayInfo: true,
            afterPageText: ' 共 {0} 页',
            beforePageText: '页 ',
            firstText: '第一页 ',
            prevText: '前一页',
            nextText: '下一页',
            lastText: '最后一页',
            refreshText: '刷新',
            displayMsg: '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
            emptyMsg: "没有记录"
        })
    
    });
    store.load({
        params: {
            start: 0,
            limit: pageSize
        }
    });
    
    grid.getSelectionModel().on('selectionchange', function(sm){
        grid.removeBtn.setDisabled(sm.getCount() < 1);
        grid.updateBtn.setDisabled(sm.getCount() != 1);
    });
    
    // 删除的处理函数
    var delHandler = function(){
        editor.stopEditing();
        var s = grid.getSelectionModel().getSelections();
        if (!s) 
            return false;
        Ext.Msg.show({
            title: '删除',
            buttons: Ext.MessageBox.YESNOCANCEL,
            msg: '确认删除？',
            fn: function(btn){
				if(btn == "no" || btn == "cancel") return;
                var ids = "";
                for (var i = 0; i < s.length; i++) { // 要删除的记录ID拼串
                    ids = ids + s[i].get(identityName) + ",";
                }
                var conn = new Ext.data.Connection();
                conn.request({
                    url: deleteMsg,
                    params: {
                        delIds: ids
                    },
                    success: function(resp, opt){
                        for (var i = 0; i < s.length; i++) { // 把store中相应的记录删掉
                            grid.getStore().remove(s[i]);
                        }
                        store.reload();
                    },
                    failure: function(resp, opt){
                        Ext.Msg.alert('错误', '删除记录失败！');
                    }
                });
            }
        });
    }
});
